package com.total.reporting.presentation;

import java.util.Iterator;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.http.HttpSession;

import org.hibernate.SQLQuery;
import org.hibernate.Session;
import org.hibernate.Transaction;

import com.total.reporting.dao.*;
import com.total.util.CryptoUtils;



public class UserController {
	
	public synchronized static User getUserById(String id) {
		/*List<User> users = getUsers("id=" + id, 0, 10);
		if (users.size() == 0)
			return null;
		return users.get(0);*/
		Session session = HibernateUtil.currentSession();
		return (User) session.get(User.class, Integer.parseInt(id));
	}

	public synchronized static List<User> getUsers(String whereClause,
			int pageNumber, int pageSize) {

		Session session = HibernateUtil.currentSession();
		String where = "";
		//String param=null;
		if (whereClause != null && whereClause.length()>0){
			
		/*	int i=whereClause.indexOf("'%");
			if(i>-1){
				int j=whereClause.indexOf("%'");
				 param=whereClause.substring(i+2,j);
				whereClause=whereClause.substring(0,i)+"?"+whereClause.substring(j+2);
			}*/
			where = "where " + whereClause;
		}
		String sql = " select * from user " + where + " order by nom";
		SQLQuery query = session.createSQLQuery(sql);
		query.addEntity(User.class);
		//query.setFirstResult((pageNumber - 1) * pageSize);
		//query.setMaxResults(pageSize);
		List<User> users = query.list();

		return users;

	}
	
	public synchronized static String getUsersHtmlTable(String whereClause) {
		Iterator<User> it = getUsers(whereClause,0,100).iterator();
		StringBuffer sb = new StringBuffer();
		sb.append("<table class='alertTable' border='1' ><tr class='tableHeader'>");
		sb.append("<td>login</td><td>name</td><td>surname</td><td>role</td><td>entity</td>");
		sb.append("</tr>");
		while (it.hasNext()) {
			sb.append("<tr class='tableRow'>");
			User aUser = it.next();
			sb.append("<td width='100px' class='labelList'><a href='javascript:getPublsiherById(\""+aUser.getId()+"\")'>" + aUser.getLogin()+"</a>"
					+ "</td ><td width='300px' class='labelList'>" + aUser.getPrenom()
					+ "</td><td width='30px' class='labelList'>" + aUser.getNom()
					+ "</td><td width='100px' class='labelList'>" + aUser.getRole());
					
			sb.append("</tr>");
		}
		sb.append("</table>");
		return sb.toString();
	}
	
	
	public synchronized static String getUsersArrayGridData(String whereClause) {
		List<User>list=getUsers(whereClause, 0, 1000000);
		Iterator<User> it = list.iterator();
		StringBuffer sb = new StringBuffer();
		sb.append("var mydata = [");
		while (it.hasNext()) {
			User aUser = it.next();
			
			sb.append("{id:\""+aUser.getId()+"\",");
			sb.append("nom:\""+aUser.getNom()+"\",");	
			sb.append("prenom:\""+aUser.getPrenom()+"\",");	
			sb.append("login:\""+aUser.getLogin()+"\",");
			sb.append("role:\""+aUser.getRole()+"\"");
			
			sb.append("},");
		}
		sb.delete(sb.length()-1, sb.length());
		  sb.append("]");
		//  System.out.println(sb.toString());
		  return sb.toString();
	}
	
	public synchronized static String getUsersxHtmlOptions(HttpSession session,String type,String currentValue) {
		String options=(String)session.getServletContext().getAttribute("list."+type);
		if(options==null){
			options=getUsersHtmlOptions("type='"+type+"'",currentValue);
			//session.getServletContext().setAttribute("list."+type,options);
		}
		
		
		
		return options;
	}
	
	public synchronized static String getUsersHtmlOptions(String whereClause,String currentValue) {
		Iterator<User> it = getUsers(whereClause, 0, 1000000).iterator();
		StringBuffer sb = new StringBuffer();
		// sb.append("<table class='table'><tr class='tableHeader'>");
		// sb.append("<td>IGG</td><td>name</td><td>surname</td><td>entity</td><td>device token</td>");
		// sb.append("</tr>");
		
		while (it.hasNext()) {
			User aUser= it.next();
			String selected="";
			String str= aUser.getPrenom()+ " "+ aUser.getNom();
			if(currentValue!=null && currentValue.equals(str))
				selected="selected='selected'";			
			sb.append("<option "+selected+">");
			sb.append(str);
			sb.append("</option>");
		}
		
		return sb.toString();
	}

	public synchronized static void updateUser(User user) {
		try {

			Session session = HibernateUtil.currentSession();
			session.clear();
			Transaction transaction = session.beginTransaction();
			User userOld = (User) session.get(User.class, new Integer(
					user.getId()));

			session.evict(userOld);
		//	user.setPassword(CryptoUtils.encrypt(user.getPassword()));
			session.saveOrUpdate(user);
			transaction.commit();

		} catch (Exception e) {
			e.printStackTrace();
		}

	}
	public synchronized static int saveUser(User user) {
		try {
			user.setPassword(CryptoUtils.encrypt(user.getPassword()));
			Session session = HibernateUtil.currentSession();
			return (Integer) session.save(user);

		} catch (Exception e) {
			e.printStackTrace();
			return -999;
		}

	}

	public synchronized static void delete(User user ) {
		try {

			Session session = HibernateUtil.currentSession();
			Transaction transaction = session.beginTransaction();
			User userOld = (User) session.get(User.class,
					new Integer(user.getId()));

			session.evict(userOld);
			session.delete(user);
			transaction.commit();

		} catch (Exception e) {
			e.printStackTrace();
		}

	}
	
	public synchronized static String getUserRoleForLoginPassword(String login,String password){
		String where="login='"+login+"'";//' and password='"+password+"'";
		List<User> list= getUsers(where, 0, 10);
		if(list.size()==0)
			return null;
		User user=list.get(0);
		//if(user.getPassword().equals(password))
		if(user.getPassword().equals(CryptoUtils.encrypt(password)))
		
			return user.getRole();
		return null;
	}
	public synchronized static boolean changePassword(String login,String password){
		String where="login='"+login+"'";
		List<User> list= getUsers(where, 0, 10);
		if(list.size()==0)
			return false;
		User user= list.get(0);
		user.setPassword(CryptoUtils.encrypt(password));
		updateUser(user);
		return true;
	}
	
	public synchronized static String validatePassword(String password){
		// It requires length of 8, at least one digit, one special character and mixed case.
		String regExp="(?=[@#!$%&+=\\-_a-zA-Z0-9]*?[A-Z])(?=[@#!$%&+=\\-_a-zA-Z0-9]*?[a-z])(?=[@#!$%&+=\\-_a-zA-Z0-9]*?[0-9])[@#!$%&+=\\-_a-zA-Z0-9]{8,}";		
		 Pattern p = Pattern.compile(regExp);
		 Matcher m = p.matcher(password);
		if( m.matches())
			return null;
		return "Password requires length of 6, at least one digit, one special character and mixed case.";
		  
	}
	
	public synchronized static User getUserForLoginAndPassword(String login, String password){
		String where="login='"+login+"'";//' and password='"+password+"'";
		List<User> list= getUsers(where, 0, 10);
		if(list.size()==0)
			return null;
		User user=list.get(0);
		//if(user.getPassword().equals(password))
		if(user.getPassword().equals(CryptoUtils.encrypt(password)))
		
			return user;
		return null;
	
	}	

}
